package experimentos;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

import rn.MLP;
import rn.SigmoidalFunction;
import util.Logger;

public class ExperimentoBack {
	private static String IRIS = "./Iris_db/Iris.txt";
	private static String IRIS_VALIDACAO = "./Iris_db/Iris_validacao.txt";
	private static String IRIS_TESTE = "./Iris_db/Iris_teste.txt";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] layersSizes = {4, 5, 1};
		Logger logger = new Logger("resultados/ExperBack", 30, 51);

		double[][] inputs = readInput(IRIS);
		double[][] outputs = readOutput(IRIS);
		
		double[][] inputsVal = readInput(IRIS_VALIDACAO);
		double[][] outputsVal = readOutput(IRIS_VALIDACAO);
		
		
		double tempoMedio = 0;
		MLP nn = null;
		for(int i=0; i<30; i++){
			nn = new MLP(layersSizes, new SigmoidalFunction(), 1 );
			
			double tempoInicio = System.currentTimeMillis();
			nn.onlineTrainingWithValidation(inputs, outputs, 0.35, 0, 5000, 0.01, 
					inputsVal, outputsVal);
			tempoMedio += (System.currentTimeMillis()-tempoInicio);
			
			logger.definirValores(i, nn.getErrorData());
			
			System.out.println(i + " - FIM");
		}
		
		try {
			logger.imprimirResultado();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Tempo = " + (tempoMedio/30));
	}

	private static double[][] readInput(String path){
		double[][] retorno = null;
		try {
			ArrayList<double[]> listaTemp = new ArrayList<>();
			File file = new File(path);
			Scanner reader = new Scanner(file);

			while(reader.hasNextLine()){
				String[] line = reader.nextLine().split("\t");
				double[] values = new double[4]; 

				values[0] = Double.parseDouble(line[0]);
				values[1] = Double.parseDouble(line[1]);
				values[2] = Double.parseDouble(line[2]);
				values[3] = Double.parseDouble(line[3]);

				listaTemp.add(values);
			}

			retorno = new double[listaTemp.size()][4];

			for(int i=0; i<retorno.length; i++){
				retorno[i] = listaTemp.get(i);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return retorno;
	}

	private static double[][] readOutput(String path){
		double[][] retorno = null;
		try {
			ArrayList<double[]> listaTemp = new ArrayList<>();
			File file = new File(path);
			Scanner reader = new Scanner(file);

			while(reader.hasNextLine()){
				String[] line = reader.nextLine().split("\t");
				double[] values = new double[1]; 

				values[0] = Double.parseDouble(line[4]);

				listaTemp.add(values);
			}

			retorno = new double[listaTemp.size()][1];

			for(int i=0; i<retorno.length; i++){
				retorno[i] = listaTemp.get(i);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return retorno;
	}

}
